package com.ibeetl.admin.aod.web;

import com.ibeetl.admin.aod.service.excel.processor.data.AodIndustryDataExcelCompareProcessor;
import com.ibeetl.admin.aod.entity.DieImportTask;
import com.ibeetl.admin.aod.service.DieImportTaskService;
import com.ibeetl.admin.aod.util.ZipFileUtil;
import com.ibeetl.admin.aod.web.query.DieImportTaskQuery;
import com.ibeetl.admin.aod.web.query.FilterQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.ArrayList;

/**
 * DieImportTask 接口
 */
@Controller
public class DieImportTaskController extends BaseController {

    private static final String MODEL = "/aod/dieImportTask";


    @Autowired
    protected DieImportTaskService dieImportTaskService;

    @Autowired
    protected AodIndustryDataExcelCompareProcessor AodIndustryDataExcelCompareProcessor;
    
    @Autowired
    FileService fileService;

    /* 页面 */
    @GetMapping(MODEL + "/index.do")
    @Function("dieImportTask.query")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/aod/dieImportTask/index.html") ;
        view.addObject("search", DieImportTaskQuery.class.getName());
        return view;
    }

    @PostMapping(MODEL + "/list.json")
    @Function("dieImportTask.query")
    @ResponseBody
    public JsonResult<PageQuery> list(DieImportTaskQuery condtion) {
        PageQuery page = condtion.getPageQuery();
        dieImportTaskService.queryByCondition(page);
        return JsonResult.success(page);
    }

    /* 筛查页面 */
    @GetMapping(MODEL + "/filter/index.do")
    @Function("dieImportTask.query")
    @ResponseBody
    public ModelAndView filterIndex() {
        ModelAndView view = new ModelAndView("/aod/dieImportTask/filter_index.html") ;
        view.addObject("search", FilterQuery.class.getName());
        return view;
    }

    @PostMapping(MODEL + "/filter/list.json")
    @Function("dieImportTask.query")
    @ResponseBody
    public JsonResult<PageQuery> filterList(FilterQuery condtion) {
        PageQuery page = condtion.getPageQuery();
        dieImportTaskService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("dieImportTask.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/aod/dieImportTask/edit.html");
        DieImportTask dieImportTask = dieImportTaskService.queryById(id);
        view.addObject("dieImportTask", dieImportTask);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("dieImportTask.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/aod/dieImportTask/add.html");
        return view;
    }



    @PostMapping(MODEL + "/add.json")
    @Function("dieImportTask.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)DieImportTask dieImportTask)
    {
        dieImportTaskService.save(dieImportTask);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("dieImportTask.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  DieImportTask dieImportTask) {
        boolean success = dieImportTaskService.update(dieImportTask);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    @GetMapping(MODEL + "/view.json")
    @Function("dieImportTask.query")
    @ResponseBody
    public JsonResult<DieImportTask>queryInfo(Integer id) {
        DieImportTask dieImportTask = dieImportTaskService.queryById( id);
        return  JsonResult.success(dieImportTask);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("dieImportTask.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        dieImportTaskService.batchDelDieImportTask(idList);
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("dieImportTask.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,DieImportTaskQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此dieImportTaskService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/aod/dieImportTask/你的excel模板文件名字.xls";
        PageQuery<DieImportTask> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<DieImportTask> list =dieImportTaskService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("DieImportTask_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("dieImportTask.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }

    @GetMapping(MODEL + "/downloadResultFile.do")
    @Function("dieImportTask.downloadResultFile")
    @ResponseBody
    public ResponseEntity<byte[]> downloadResultFile(String batchNo) {

        try {
            DieImportTask dieImportTask = dieImportTaskService.findByBatchNo(batchNo);
            if (null != dieImportTask) {
                String resultNames = dieImportTask.getResultFileNames();
                String basePath = dieImportTask.getFileSavePath();
                String[] resultNameArr = resultNames.split(",");
                List<File> fileList = new ArrayList<>();
                if (null != resultNameArr && resultNameArr.length > 1) {
                    for (String fileName : resultNameArr) {
                        File file = new File(basePath + "/" + fileName);
                        if (!file.exists()) {
                            throw new PlatformException("找不到文件：" + fileName);
                        }

                        fileList.add(file);
                    }
                    String zipFileName = "result.zip";
                    ZipFileUtil.zip(basePath + "/" + zipFileName, fileList, "gbk", false);

                    HttpHeaders headers = new HttpHeaders();
                    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                    headers.setContentDispositionFormData("attachment", zipFileName);

                    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(basePath + "/" + zipFileName)), headers, HttpStatus.OK);
                }
            }
        } catch (Exception e) {
            log.error("下载结果文件失败：",e);
        }
        HttpHeaders headers = new HttpHeaders();
        return new ResponseEntity<>("找不到结果文件".getBytes(), headers, HttpStatus.NOT_FOUND);
    }
    
}
